/*****************************************************************
                        Round Robin, q = 4
PURPOSE: This is the algorithm for feedback CPU scheduling. It inherits
data and functionalities from base class Scheduler.
 *****************************************************************/
import java.util.ArrayList;

public class RR4 extends Scheduler implements Runnable {

	/*--------------------------------------------------------
	                     Constructor
	PURPOSE:  To ask help from views, set up data, and begin simulation
	PARAMTERS: references the input queue, stats and anime view. gets
	value of starting clock time.
	--------------------------------------------------------*/
	public RR4(ArrayList<Process> q, statsFrame s, animeFrame a, inputFrame i,
			int c) {
		super(q, s, a, i, c);

		thread = new Thread(this, "RR4");
		thread.start();
	} // constructor

	/*--------------------------------------------------------
	                     Thread Run
	PURPOSE:  To run light-weight thread simulation
	--------------------------------------------------------*/
	public void run() {
		int all = queue.size(), interval = 0, next = 0;
		boolean interrupt = false;

		do {
			clock++;
			T = processready(clock);
			if (T != null) {
				readyQueue.add(T);
				queue.remove(T);
				an.upstatus("Time " + T.getArrival() + ":Process "
						+ T.getName() + " ready.");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
				;
			} // put in ready queue
			if (idle || interrupt) {
				if (interrupt) {
					interrupt = false;
					interval = 0;
				} // reset interval
				if (readyQueue.size() == 0)
					continue;
				if (next < readyQueue.size() - 1)
					next++;
				else
					next = 0;
				P = (Process) readyQueue.get(next);
				idle = false;
			} // get next process
			P.servicing();
			interval++;
			an.drawbar(P, clock);
			an.upstatus("Time " + clock + ":Serving process " + P.getName()
					+ ".");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException ex) {
			}
			;
			if (P.getTminus() == 0) {
				an.upstatus("Time " + (clock + 1) + ":Process " + P.getName()
						+ " done.");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
				;
				P.report(clock + 1); // anticipate completion
				finishQueue.add(P);
				readyQueue.remove(P);
				next--; // recenter ptr
				idle = true;
				interval = 0;
			} // put in finish queue
			else if (interval == 4)
				interrupt = true;
		} while (finishQueue.size() < all);
		an.upstatus("Algorithm finished.");
		st.report(finishQueue, "Round Robin,q = 4");
		in.resetGUI();
	} // run thread

} // RR4 class
